﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.VisualBasic.FileIO;
using VirtualFileSystem;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    ///虚拟文件系统
    /// </summary>
    public static class VirtualFileSystemExtensions
    {

        /// <summary>
        /// 使用虚拟文件系统
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseVirtualFileSystem(this IApplicationBuilder app, Action<VirtualFileSystemOption> configActionn)
        {
            if (configActionn == null)
            {
                throw new ArgumentNullException(nameof(configActionn));
            }
            VirtualFileSystemOption option=new();
            configActionn(option);
            UseVirtualFileSystem(app, option);
            return app;
        }

        /// <summary>
        /// 使用虚拟文件系统
        /// </summary>
        public static IApplicationBuilder UseVirtualFileSystem(this IApplicationBuilder app, VirtualFileSystemOption option)
        {           
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (option == null)
            {
                throw new ArgumentNullException(nameof(option));
            }
            if (option.FileProviders == null || option.FileProviders.Count==0)
            {
                throw new ArgumentNullException(nameof(option.FileProviders));
            }

            var compositeFileProvider = new CompositeFileProvider(option.FileProviders);
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = compositeFileProvider,
            });

            if (option.EnableDirectoryBrowser)
            {
                app.UseDirectoryBrowser(new DirectoryBrowserOptions()
                {
                    FileProvider = compositeFileProvider
                });
            }
            return app;
        }

    }
}
